import traceback
import ujson as json
from django.http import HttpResponse

from django.views import View
from base import errors
from base.check_params import CheckParams


class BaseApi(View):
    need_params = {}

    def dispatch(self, request, *args, **kwargs):
        code = 0
        msg = ''
        data = {}

        try:
            if request.method.lower() in self.http_method_names:
                handler = getattr(self, request.method.lower(),
                                  self.http_method_not_allowed)
            else:
                handler = self.http_method_not_allowed

            params = self.check_params(request)
            data = handler(request, params, *args, **kwargs)
        except errors.BaseError as e:
            code = e.errcode
            msg = e.errmsg
        except Exception as e:
            print(traceback.print_exc())
            code = errors.BaseError.errcode
            msg = errors.BaseError.errmsg
        result = {
            'code': code,
            'msg': msg,
            'data': data,
        }
        return HttpResponse(json.dumps(result), content_type='application/json')

    def check_params(self, request):
        '''
        校验参数
        '''
        params = {}
        data = {}
        # 先解析url中的参数
        for k, v in request.GET.items():
            data[k] = v
        # 再解析body中的参数，存在相同参数时，以body中为准
        if request.body:
            data.update(json.loads(request.body))
        print(data)
        for key in self.need_params.keys():
            value = data.get(key)
            name, condition = self.need_params.get(key)
            method, *condition = condition.split(' ')
            method = 'check_{}'.format(method)
            value = getattr(CheckParams, method)(name, value, condition)
            params[key] = value
        return params
